<script setup>
import { useUserStore } from '@/stores'
import { getAddressTree, getLikeListAPI, getMemberApi, updateMemberInfoAPI, uploadPortrait } from '@/apis/user'
import { onMounted, ref, toRaw } from 'vue'
import { ElMessage } from 'element-plus'
import { removeJwt } from '@/utils/jwt'
import router from '@/router'
// 定义变量
const likeList = ref([])
const userStore = useUserStore()
// 获取猜你喜欢商品数据
const getLikeList = async () => {
  const res = await getLikeListAPI({ limit: 4 })
  likeList.value = res.result
}


onMounted(() => getLikeList())
const dialogType = ref('') // 'profile' 或 'security'
// 对话框相关变量
const memberDlgShow = ref(false)
const memberDlgTitle = ref('安全设置')
const memberModel = ref({
  id: '',
  name: '',
  sex: '',
  birthday: '',
  portrait: '',
  phone: '',
  password: '',
  addressId: ''
})

// 打开安全设置对话框

// 打开个人信息设置对话框
const openProfileSettings = () => {
  dialogType.value = 'profile'
  memberDlgTitle.value = '信息管理'
  loadAddressTree();

  // 初始化表单数据为当前用户信息
  const userInfo = userStore.userInfo.message
  if (!userInfo.address) {
    userInfo.address = {}
  }
  memberModel.value = {
    id: userInfo.id || '',
    name: userInfo.name || '',
    sex: userInfo.sex || '',
    birthday: userInfo.birthday || '',
    portrait: userInfo.portrait || '',
    phone: userInfo.phone || '',
    addressId: userInfo.addressId || '',
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  // 如果有地址信息，设置到 model 中
  if (userInfo.address && userInfo.address.id) {
    memberModel.value.addressId = userInfo.address.id
    selectedAddressName.value = userInfo.address.name
    addressQuery.value = userInfo.address.name
  }

  memberDlgShow.value = true
}
const openSecuritySettings = () => {
  dialogType.value = 'security'
  memberDlgTitle.value = '安全设置'
  memberModel.value = {
    id: userStore.userInfo.message.id || '',
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
    name: '',
    sex: '',
    birthday: '',
    portrait: '',
    phone: '',
    addressId: '',
    address: ''
  }
  memberDlgShow.value = true
}

async function refreshUserInfo() {
  try {
    // 获取当前用户的ID
    const userId = userStore.userInfo.message.id

    // 调用API获取最新的用户信息
    const response = await getMemberApi(userId)

    // 更新store中的用户信息
    userStore.userInfo.message = response.data
    console.log(userStore.userInfo.message.address.name)
    ElMessage.success("信息已更新")
  } catch (error) {
    console.error("刷新用户信息失败:", error)
    ElMessage.error("刷新信息失败")
  }
}

// 提交表单
function submitForm() {
  if (dialogType.value === 'security') {
    submitPasswordChange()
  } else {
    submitAdd()
  }
}

const addressTree = ref([])
const addressTreeRef = ref()
const selectedAddress = ref()
const selectedAddressName = ref('')
const addressQuery = ref('')
// 树形组件属性配置
const treeProps = {
  value: 'id',
  label: 'name',
  children: 'children'
}

// 获取地址树形结构
async function loadAddressTree() {
  try {
    const resp = await getAddressTree()
    console.log(resp)
    if (resp.success) {
      addressTree.value = resp.data
    }
  } catch (error) {
    ElMessage.error("获取地址数据失败")
    console.error(error)
  }
}

//处理地址点击
function handleAddressNodeClick(data) {
  selectedAddress.value = data.id
  selectedAddressName.value = data.name
  memberModel.value.addressId = data.id
  addressQuery.value = data.name
}

//地址查询变化
function onAddressQueryChanged(query){
  if(addressTreeRef.value){
    addressTreeRef.value.filter(query)
  }
}

// 地址树过滤方法
const addressFilterMethod = (query, node) => {
  return node.label.includes(query)
}

// 添加一个新的变量来存储待上传的头像文件
let pendingAvatarFile = ref(null);

async function handleAvatarUpload(options) {
  const { file } = options;
  // 保存待上传文件
  pendingAvatarFile.value = file;

  // 创建本地预览URL
  const reader = new FileReader();
  reader.onload = (e) => {
    memberModel.value.portrait = e.target.result;
  };
  reader.readAsDataURL(file);

  ElMessage.info("头像已选择，将在保存时上传");


}
//上传头像并获取URL
async function uploadAvatarAndGetUrl(file) {
  try {
    const formData = new FormData();
    formData.append('file', file);

    // 如果是编辑模式且有用户ID，则添加ID参数

    formData.append('id', memberModel.value.id);

    const resp = await uploadPortrait(formData);
    if (resp.success) {
      // 只返回URL，不直接修改memberModel
      return resp.data; // 返回头像URL
    } else {
      ElMessage.error(resp.msg || "头像上传失败");
      return null;
    }
  } catch (error) {
    ElMessage.error("头像上传失败: " + error.message);
    return null;
  }
}
// 清除本地预览
function resetPendingAvatar() {
  pendingAvatarFile.value = null;
  // 只清除本地预览URL（以data:开头的）
  if (memberModel.value.portrait && memberModel.value.portrait.startsWith('data:')) {
    memberModel.value.portrait = null;
  }
}
let memberFormRef = ref();
function submitAdd() {
  memberFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // eslint-disable-next-line no-undef
        let params = toRaw(memberModel.value);

        // 确保地址信息包含在提交参数中
        if (memberModel.value.addressId) {
          params.address = {
            id: memberModel.value.addressId,
            name: selectedAddressName.value
          }
        }
        if (pendingAvatarFile.value) {
          const avatarUrl = await uploadAvatarAndGetUrl(pendingAvatarFile.value);
          if (avatarUrl) {
            params.portrait = avatarUrl;
          } else {
            ElMessage.error("头像上传失败");
            return;
          }
        }
        let resp = await updateMemberInfoAPI(params);

        if (resp.success) {
          ElMessage.success("修改成功");
          memberDlgShow.value = false;
          resetPendingAvatar(); // 重置待上传文件（清除本地预览）
          await refreshUserInfo()
        } else {
          ElMessage.error(resp.msg || "修改失败");
        }
      } catch (error) {
        ElMessage.error("修改失败: " + (error.message || "未知错误"));
      }
    } else {
      ElMessage.error("请填写正确的数据");
    }
  });
}

async function submitPasswordChange() {
  // 验证密码输入
  if (!memberModel.value.oldPassword) {
    ElMessage.error('请输入原密码')
    return
  }
  if (!memberModel.value.newPassword) {
    ElMessage.error("请输入新密码")
    return
  }
  if (memberModel.value.newPassword !== memberModel.value.confirmPassword) {
    ElMessage.error("两次输入的新密码不一致")
    return
  }

  try {
    // 这里应该调用修改密码的API，由于没有看到对应API，暂时省略
    // 假设有一个 changePasswordAPI 函数


    const resp = await updateMemberInfoAPI({
      id: memberModel.value.id,
      oldPassword: memberModel.value.oldPassword,
      newPassword: memberModel.value.newPassword
    })

    if (resp.success) {
      ElMessage.success("密码修改成功，请重新登录")
      // 清除JWT并跳转到登录页
      removeJwt()
      router.push('/login')
    } else {
      ElMessage.error(resp.msg || "密码修改失败")
    }

    // 模拟修改成功后的操作
    ElMessage.success("密码修改成功，请重新登录")
    memberDlgShow.value = false
    // 清除JWT并跳转到登录页
    removeJwt()
    router.push('/login')
  } catch (error) {
    ElMessage.error("密码修改失败: " + (error.message || "未知错误"))
  }
}
</script>

<template>
  <div class="home-overview">
    <!-- 用户信息 -->
    <div class="user-meta">
      <div class="portrait" >
        <img :src="userStore.userInfo.message.portrait" />
      </div>
      <h4>{{ userStore.userInfo.message.account }}</h4>
    </div>
    <div class="item">
      <a href="javascript:;">
        <span class="iconfont icon-hy"></span>
        <p>会员中心</p>
      </a>
      <a href="javascript:;" @click="openSecuritySettings">
        <span class="iconfont icon-aq"></span>
        <p>安全设置</p>
      </a>
      <a href="javascript:;"  @click="openProfileSettings">
        <span class="iconfont icon-dw"></span>
        <p>信息管理</p>
      </a>
    </div>
  </div>
  <!-- 新增用户信息展示区域 -->
  <div class="user-info-container">
    <div class="user-info-card">
      <div class="info-item">
        <span class="label">用户名：</span>
        <span class="value">{{ userStore.userInfo.message.account }}</span>
      </div>
      <div class="info-item">
        <span class="label">姓名：</span>
        <span class="value">{{ userStore.userInfo.message.name || '未填写' }}</span>
      </div>
      <div class="info-item">
        <span class="label">性别：</span>
        <span class="value">{{ userStore.userInfo.message.sex || '未填写' }}</span>
      </div>
      <div class="info-item">
        <span class="label">出生日期：</span>
        <span class="value">{{ userStore.userInfo.message.birthday || '未填写' }}</span>
      </div>
      <div class="info-item">
        <span class="label">手机号：</span>
        <span class="value">{{ userStore.userInfo.message.phone || '未填写' }}</span>
      </div>
      <div class="info-item">
        <span class="label">头像：</span>
        <span class="value">
          <img v-if="userStore.userInfo.message.portrait" :src="userStore.userInfo.message.portrait" alt="头像" style="width: 40px; height: 40px; border-radius: 50%;">
          <span v-else>无</span>
        </span>
      </div>
      <div class="info-item">
        <span class="label">地址：</span>
        <span class="value">{{ userStore.userInfo.message.address.name || '未填写' }}</span>
      </div>
    </div>
  </div>
  <div class="like-container">
    <div class="home-panel">

      <div class="goods-list">
        <GoodsItem v-for="good in likeList" :key="good.id" :good="good" />
      </div>
    </div>
  </div>


  <el-dialog v-model="memberDlgShow" :title="memberDlgTitle" width="600"
             :close-on-click-modal="false" draggable align-center  @close="resetMemberForm">
    <el-form label-width="100px" label-position="right"  :model="memberModel" ref="memberFormRef" :rules="rules">

      <el-row v-if="dialogType === 'profile'">
        <!-- 信息管理表单 -->
        <el-col :span="14" class="la">
          <el-form-item label="姓名：" prop="name" >
            <el-input v-model="memberModel.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="性别：" prop="sex">
            <el-radio-group v-model="memberModel.sex">
              <el-radio label="男" value="男" />
              <el-radio label="女" value="女"/>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="出生日期：" prop="birthday">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              v-model="memberModel.birthday"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-upload
            class="avatar"
            :http-request="handleAvatarUpload"
            :show-file-list="false"
            :headers="headers">
            <img v-if="memberModel.portrait" :src="memberModel.portrait" alt="会员头像" width="150px"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-col>
      </el-row>

      <el-form-item v-if="dialogType === 'profile'" label="手机号：" prop="phone">
        <el-input placeholder="请输入手机号" v-model="memberModel.phone"></el-input>
      </el-form-item>

      <div v-if="dialogType === 'profile'">
        <el-form-item label="地址：" prop="address.name">
          <div class="address-tree-container">
            <el-input
              v-model="addressQuery"
              placeholder="请输入地址关键字搜索"
              clearable
              @input="onAddressQueryChanged"
            />
            <el-tree-v2
              ref="addressTreeRef"
              :data="addressTree"
              :props="treeProps"
              :height="200"
              :filter-method="addressFilterMethod"
              highlight-current
              expand-on-click-node
              @node-click="handleAddressNodeClick"
            >
              <template #default="{ node }">
                <span>{{ node.label }}</span>
              </template>
            </el-tree-v2>
            <div v-if="selectedAddressName" class="selected-address">
              已选择: {{ selectedAddressName }}
            </div>
          </div>
        </el-form-item>
      </div>

      <!-- 安全设置(密码修改)表单 -->
      <div v-if="dialogType === 'security'">
        <el-form-item label="原密码：" prop="oldPassword">
          <el-input type="password" placeholder="请输入原密码" v-model="memberModel.oldPassword"></el-input>
        </el-form-item>

        <el-form-item label="新密码：" prop="newPassword">
          <el-input type="password" placeholder="请输入新密码" v-model="memberModel.newPassword"></el-input>
        </el-form-item>

        <el-form-item label="确认密码：" prop="confirmPassword">
          <el-input type="password" placeholder="请再次输入新密码" v-model="memberModel.confirmPassword"></el-input>
        </el-form-item>
      </div>

    </el-form>

    <template #footer>
      <div>
        <el-button type="primary" @click="submitForm">{{ dialogType === 'security' ? '修改密码' : '保存信息' }}</el-button>
        <el-button type="primary" @click="memberDlgShow=false">取消</el-button>
      </div>
    </template>
  </el-dialog>


</template>

<style scoped lang="scss">
.user-info-container {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.user-info-card {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;

  .label {
    width: 80px;
    color: #666;
    font-weight: 500;
  }

  .value {
    flex: 1;
    color: #333;
  }

  img {
    border-radius: 50%;
  }
}
.home-overview {
  height: 132px;
  background: url(@/assets/images/center-bg.png) no-repeat center / cover;
  display: flex;

  .user-meta {
    flex: 1;
    display: flex;
    align-items: center;

    .portrait {
      width: 85px;
      height: 85px;
      border-radius: 50%;
      overflow: hidden;
      margin-left: 60px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    h4 {
      padding-left: 26px;
      font-size: 18px;
      font-weight: normal;
      color: white;
    }
  }

  .item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-around;

    &:first-child {
      border-right: 1px solid #f4f4f4;
    }

    a {
      color: white;
      font-size: 16px;
      text-align: center;

      .iconfont {
        font-size: 32px;
      }

      p {
        line-height: 32px;
      }
    }
  }
}

.like-container {
  margin-top: 20px;
  border-radius: 4px;
  background-color: #fff;
}

.home-panel {
  background-color: #fff;
  padding: 0 20px;
  margin-top: 20px;
  height: 400px;

  .header {
    height: 66px;
    border-bottom: 1px solid #f5f5f5;
    padding: 18px 0;
    display: flex;
    justify-content: space-between;
    align-items: baseline;

    h4 {
      font-size: 22px;
      font-weight: 400;
    }
  }

  .goods-list {
    display: flex;
    justify-content: space-around;
  }
}
</style>
